package cn.zl.common.manage;

import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 所有的流管理
 */
@Component
public class StreamManage {

    private final Map<String, Map<String, StreamInfo>> cache = new ConcurrentHashMap<>();

    public int getState(String app, String stream) {
        Map<String, StreamInfo> streamInfoMap = cache.get(app);
        if (streamInfoMap != null) {
            StreamInfo streamInfo = streamInfoMap.get(stream);
            if (streamInfo != null) {
                return streamInfo.schemas.isEmpty() ? 0 : 1;
            }
        }
        return 0;
    }

    public void add(String app, String stream, String schema) {
        Map<String, StreamInfo> streamInfoMap = cache.computeIfAbsent(app, k -> new ConcurrentHashMap<>());
        StreamInfo streamInfo = streamInfoMap.computeIfAbsent(stream, k -> new StreamInfo());
        streamInfo.schemas.put(schema, schema);
    }

    public void remove(String app, String stream, String schema) {
        Map<String, StreamInfo> streamInfoMap = cache.get(app);
        if (streamInfoMap != null) {
            StreamInfo streamInfo = streamInfoMap.get(stream);
            if (streamInfo != null) {
                streamInfo.schemas.remove(schema);
            }
        }
    }


    public static class StreamInfo {
        /**
         * 协议类型
         */
        public Map<String, String> schemas = new ConcurrentHashMap<>();
    }
}
